'''
平安e生保2017版
'''

import sys
sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
from urllib.parse import urlencode
import requests, json
from common.helper import Helper

class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "平安e生保2017版"

    def genProductInfo(self):

        plan = {
            # 年龄段 0 -60
            "year":[str(i) for i in range(0,61)],
            #有无社保
            "socialSec":["Y","N"],
            #保障计划代码
            "planCode":["03","04"]

        }

        for v in  product( plan["year"],plan["socialSec"],plan["planCode"]):

            payObject = "配偶/父母/子女/本人"

            if v[2] == "03":

                introduce = {

                    "A计划":"100,0000元保额",
                }

            else:

                introduce = {

                    "B计划": "300,0000元保额",
                }

            data = "'" + json.dumps( introduce,ensure_ascii=False) + "'"

            self.mysql.cursor.execute( domain[self.name]["insert_sql"].format( v[0],v[1],v[2],payObject,data))

            self.mysql._conn.commit()

            print( domain[self.name]["insert_sql"].format( v[0],v[1],v[2],payObject,data) )

    #执行爬虫
    def requestJson(self,dt=None):

        data = {

            "birthDate": "{year}-01-01".format( year=str(2020-int(dt["year"]))),
            "coverageAmount": dt["planCode"],
            "socialSecurity": dt["socialSec"],
        }


        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=urlencode(data).replace('+',''))



        if r.status_code == 200:

            price = Helper.decimalParse( r.text )

            data = {

                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            self.mysql.updatePrice( data )

        else:

            # 任务执行失败
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            self.mysql.updateTask(data)

            print("产品价格更新失败:", dt["id"])

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)
